export const taskPool = async <T>(
  poolTask: (...args: any[]) => Promise<T>,
  dataList: any[],
  getTaskArgs: Function
) => {
  try {
    const taskPool: Promise<T | any>[] = [];
    const maxTaskNum = 4;
    let index = 0;
    while (index < dataList.length) {
      const currentIndex = index;
      const args = getTaskArgs(dataList[currentIndex], index, dataList);
      const task = poolTask(args);
      taskPool.push(task);
      task.then((_res) => {
        taskPool.splice(
          taskPool.findIndex((item) => item === task),
          1
        );
      });
      if (taskPool.length === maxTaskNum) {
        await Promise.race(taskPool);
      }
      index++;
    }
    await Promise.all(taskPool);
    return true;
  } catch (err) {
    return false;
  }
};

export const parseDateArrayToDateString = (dateArray: number[]) => {
  const date = new Date(
    dateArray[0],
    dateArray[1] - 1,
    dateArray[2],
    dateArray[3],
    dateArray[4],
    dateArray[5]
  );
  return parseDateToLocalString(date);
};

export const parseDateToLocalString = (date: Date) => {
  const now = new Date();
  const offset = now.getTime() - date.getTime();
  const seconds = Math.floor(offset / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const months = Math.floor(days / 30);
  const years = Math.floor(months / 12);

  // 定义时间单位数组
  const units = [
    { label: "秒", threshold: seconds },
    { label: "分钟", threshold: minutes },
    { label: "小时", threshold: hours },
    { label: "天", threshold: days },
    { label: "月", threshold: months },
    { label: "年", threshold: years },
  ];

  // 找到最大但不超过实际值的单位
  let result = units.reverse().find((unit) => unit.threshold >= 1);

  // 处理特殊情况，如小于一秒
  if (!result) {
    return "刚刚";
  }
  // 格式化输出
  return `${Math.floor(result.threshold)} ${result.label}前`;
};
